package web

import (
	"fmt"
	"jgt-oper/src/bll"
	"jgt-oper/src/context"
	"jgt-oper/src/schema"
)

// EVController 企业来访控制器
type EVController struct {
	EVBll         *bll.EVisit     `inject:""`
	EnterpriseBll *bll.Enterprise `inject:""`
}

// QVisitPage 查询分页
func (a *EVController) QVisitPage(ctx *context.Context) error {
	ctx.WriteOperateLog("EVController.QVisitPage", "企业来访列表")
	//	查询列表的页码和列表大小
	currentPage, pageSize := ctx.GetPageIndex(), ctx.GetPageSize()
	params := new(schema.EVQParams)
	params.PersonnelName = ctx.Query("personnel_name")
	params.ContractTel = ctx.Query("contract_tel")
	params.FromEnterprise = ctx.Query("from_enterprise")
	params.VisitingEnterpriseID = ctx.Query("visiting_enterprise_id")
	params.PersonnelTotal = ctx.QueryInt("personnel_total")
	params.MainContent = ctx.Query("main_content")
	params.StartTime = ctx.QueryInt64("start_time")
	params.EndTime = ctx.QueryInt64("end_time")
	total, items, err := a.EVBll.QVisitPage(params, currentPage, pageSize)
	fmt.Println("total:", "items:", "err:", total, items, err)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	itemsList := make([]map[string]interface{}, 0)
	for _, item := range items {
		fmt.Println("item:", item)
		tempMap := make(map[string]interface{})
		tempMap["record_id"] = item.RecordID
		tempMap["personnel_name"] = item.PersonnelName
		tempMap["contract_tel"] = item.ContractTel
		tempMap["from_enterprise"] = item.FromEnterprise
		tempMap["personnel_total"] = item.PersonnelTotal
		//	查询企业信息
		enterpriseDetail, err := a.EnterpriseBll.Get(item.VisitingEnterpriseID)
		if err != nil || enterpriseDetail == nil {
			return ctx.ResErrInternalServer(err)
		}

		tempMap["visiting_enterprise_name"] = enterpriseDetail.Name
		tempMap["start_time"] = item.StartTime
		tempMap["end_time"] = item.EndTime
		tempMap["main_content"] = item.MainContent
		if item.Status == 1 {
			tempMap["status"] = "正常"
		} else if item.Status == 2 {
			tempMap["status"] = "作废"
		}
		//	TODO	门禁路径，目前只是构造模拟信息
		enterPathArray := make([]map[string]interface{}, 0)
		nodePath := make(map[string]interface{})
		nodePath["enter_time"] = 1541059365
		nodePath["entrance_name"] = "门禁名称"
		nodePath2 := make(map[string]interface{})
		nodePath2["enter_time"] = 1541059365
		nodePath2["entrance_name"] = "门禁名称3333"
		enterPathArray = append(enterPathArray, nodePath)
		enterPathArray = append(enterPathArray, nodePath2)
		tempMap["enter_path"] = enterPathArray

		itemsList = append(itemsList, tempMap)
	}
	result := map[string]interface{}{
		"list": itemsList,
		"pagination": map[string]interface{}{
			"total":    total,
			"current":  currentPage,
			"pageSize": pageSize,
		},
	}

	return ctx.ResSuccess(result)
}

// Cancel 取消来访
func (a *EVController) Cancel(ctx *context.Context) error {
	ctx.WriteOperateLog("EVController.QVisitPage", "企业来访列表")
	err := a.EVBll.Cancel(ctx.Param("id"))
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResOK()
}
